package com.mz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mz.common.dto.GlobalException;
import com.mz.common.dto.PaginationVo;
import com.mz.dao.OmsGoodsInfoDao;
import com.mz.dao.OmsOrderGoodsDao;
import com.mz.dao.OmsOrderInfoDao;
import com.mz.entity.OmsGoodsCart;
import com.mz.entity.OmsGoodsInfo;
import com.mz.entity.OmsOrderGoods;
import com.mz.entity.OmsOrderInfo;
import com.mz.entity.vo.OrderGoodsInfo;
import com.mz.entity.vo.OrderInfoVo;
import com.mz.entity.vo.OrderQueryVo;
import com.mz.entity.vo.UmsRoleInfoQuery;
import com.mz.service.OmsGoodsCartService;
import com.mz.service.OmsGoodsInfoService;
import com.mz.service.OmsOrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * (OmsOrderInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-12-13 13:38:31
 */
@Service
public class OmsOrderInfoServiceImpl implements OmsOrderInfoService {

    @Resource
    private OmsOrderInfoDao omsOrderInfoDao;
    @Resource
    private OmsOrderGoodsDao omsOrderGoodsDao;
    @Resource
    private OmsGoodsInfoService omsGoodsInfoService;

    @Override
    public IPage getOrderPagination(PaginationVo paginationVo, OrderQueryVo orderQueryVo) throws Exception {

        IPage<OmsOrderInfo> page = new Page( paginationVo.getPageIndex(), paginationVo.getPageSize() );
        LambdaQueryWrapper<OmsOrderInfo> lqs = new LambdaQueryWrapper<>();
        lqs.eq( OmsOrderInfo::getUserId, orderQueryVo.getUserId() );
        lqs.eq(  orderQueryVo.getOrderStatus() != null && !orderQueryVo.getOrderStatus().equals(0), OmsOrderInfo::getOrderStatus, orderQueryVo.getOrderStatus() );
        lqs.orderByDesc( OmsOrderInfo::getCreateTime );

        omsOrderInfoDao.selectPage(page, lqs);
        List<OmsOrderInfo> records = page.getRecords();
        if( records.size() == 0 ){
            return  page;
        }
        Set<Long> orderIds = records.stream().map(item -> item.getId()).collect(Collectors.toSet());

        LambdaQueryWrapper<OmsOrderGoods> orderGoodsLqs = new LambdaQueryWrapper<>();
        orderGoodsLqs.in( OmsOrderGoods::getOrderId, orderIds );
        List<OmsOrderGoods> omsOrderGoodsList = omsOrderGoodsDao.selectList(orderGoodsLqs);
        for( OmsOrderInfo omsOrderInfo : records ){
            List<OmsOrderGoods> collect = omsOrderGoodsList.stream().filter(item -> item.getOrderId().equals(omsOrderInfo.getId())).collect(Collectors.toList());
            omsOrderInfo.setOrderGoodsList(collect);
        }

        return page;
    }

    @Override
    public OmsOrderInfo getOrderDetail(Long id, Long userId) throws Exception {

        //先获取订单
        OmsOrderInfo omsOrderInfo = omsOrderInfoDao.selectById(id);
        if( omsOrderInfo == null || !omsOrderInfo.getUserId().equals(userId)){
            throw GlobalException.gen(10051, "订单不存在");
        }

        //从订单获取订单商品
        Long orderId = omsOrderInfo.getId();
        LambdaQueryWrapper<OmsOrderGoods> lqs = new LambdaQueryWrapper<>();
        lqs.eq(OmsOrderGoods::getOrderId, orderId);
        List<OmsOrderGoods> omsOrderGoodsList = omsOrderGoodsDao.selectList(lqs);
        omsOrderInfo.setOrderGoodsList(omsOrderGoodsList);
        return omsOrderInfo;
    }

    @Override
    @Transactional
    public void addOrder(OrderInfoVo orderInfoVo) throws Exception {

        //1、现根据用户来获取购物车的商品
        List<OrderGoodsInfo> orderGoodsInfoList = orderInfoVo.getOrderGoodsInfoList();
        if( orderGoodsInfoList == null || orderGoodsInfoList.size() == 0 ){
            throw GlobalException.gen(10041, "购物车为空");
        }

        //2、根据商品id，找到商品
        Set<Long> goodsIds = orderGoodsInfoList.stream().map( item->item.getProductId() ).collect(Collectors.toSet());
        List<OmsGoodsInfo> omsGoodsInfos = omsGoodsInfoService.getGoodsListByIds(goodsIds);
        if( omsGoodsInfos == null ){
            throw GlobalException.gen(10042, "商品已下架");
        }
        for( OmsGoodsInfo omsGoodsInfo : omsGoodsInfos ){
            //如果商品已经下架
            if( omsGoodsInfo.getGrounding() == null || omsGoodsInfo.getGrounding().equals(0) ){
                throw GlobalException.gen(10042, omsGoodsInfo.getName()+ "已下架");
            }
            //如果商品库存不够
            if( omsGoodsInfo.getStore() <= 0 ){
                throw GlobalException.gen(10042, omsGoodsInfo.getName()+ "库存不够");
            }
        }

        Integer goodsAmount = 0;
        Integer goodsAmountPrice = 0;
        List<OmsOrderGoods> omsOrderGoodsList = new ArrayList<OmsOrderGoods>();
        for ( OrderGoodsInfo orderGoodsInfo : orderGoodsInfoList ) {

            //找出商品
            Optional<OmsGoodsInfo> first = omsGoodsInfos.stream().filter(item -> {
                System.out.println(item.getId() + "  "+orderGoodsInfo.getProductId());
                return item.getId().equals(orderGoodsInfo.getProductId());
            }).findFirst();

            if( !first.isPresent() ){
                throw GlobalException.gen(10043, "商品已下架");
            }
            OmsGoodsInfo omsGoodsInfo = first.get();

            //订单中商品信息备份。
            Integer goodsAmoundPrice = orderGoodsInfo.getProductAmount() * omsGoodsInfo.getActualPrice();
            OmsOrderGoods omsOrderGoods = new OmsOrderGoods();
            omsOrderGoods.setProductId(omsGoodsInfo.getId())
                    .setProductImg(omsGoodsInfo.getCoverUrl())
                    .setProductName(omsGoodsInfo.getName())
                    .setProductPrice(omsGoodsInfo.getActualPrice()) //产品原价
                    .setProductActualPrice(omsGoodsInfo.getActualPrice()) //没优惠的前提下就是原价
                    .setProductAmount(orderGoodsInfo.getProductAmount())
                    .setProductAmountPrice(goodsAmoundPrice); //产品实际价格
            omsOrderGoodsList.add(omsOrderGoods);

            //计算总量
            goodsAmount += orderGoodsInfo.getProductAmount();
            //计算总价格
            goodsAmountPrice += orderGoodsInfo.getProductAmount() * omsGoodsInfo.getActualPrice();
        }

        OmsOrderInfo omsOrderInfo = new OmsOrderInfo();
        //产品信息
        omsOrderInfo.setUserId(orderInfoVo.getUserId())
                        .setIsGroup(0)
                        .setIsSeckill(0)
                        .setGoodsAmount(goodsAmount)
                        .setGoodsAmountPrice(goodsAmountPrice)
                        .setOrderStatus(1); //待支付订单 ;
        omsOrderInfoDao.insert( omsOrderInfo );


        //增加产品中的商品信息
        for(OmsOrderGoods omsOrderGoods : omsOrderGoodsList){
            omsOrderGoods.setOrderId( omsOrderInfo.getId() );
            omsOrderGoodsDao.insert(omsOrderGoods);
        }

        return;
    }
}

